var http = require('http');
var fs = require('fs');
var url = require('url');
var querystring = require('querystring');

read = cb => {
    fs.readFile('./data.json', 'utf8', (err, data) => {
        if (err || data.length == 0) {
            cb([])
        } else {
            cb(JSON.parse(data));
        }
    })
}
function write(data, cb) {
    fs.writeFile('./data.json', JSON.stringify(data), cb)
}


var server = http.createServer((req, res) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.setHeader("X-Powered-By", ' 3.2.1');
    if (req.method == 'OPTIONS') return res.end();
    var { query, pathname } = url.parse(req.url, true);

    if (pathname === '/getlist') {
        res.setHeader('Content-type', 'application/json;charset=utf8');
        read(list => {
            res.end(JSON.stringify({
                "status": "success",
                "result": {
                    "data": list,
                    "code": 10002,
                    "msg": "成功",
                },
            }))
        })
        return
    };

    if (pathname === '/removelist') {
        res.setHeader('Content-type', 'application/json;charset=utf8');
        read(list => {
            list = list.filter(item => item.id != query.id);
            write(list, (err) => {
                res.end(JSON.stringify({}));
            })
            res.end(JSON.stringify({
                "status": "success",
                "result": {
                    "code": 10002,
                    "msg": "删除成功",
                },
            }))
        })
        return
    };

    if (pathname === '/addlist') {
        res.setHeader('Content-type', 'application/json;charset=utf8');
        var str = '';
        req.on('data', chunk => {
            str += chunk;
        });
        req.on('end', () => {
            str = JSON.parse(str);
            read(list => {
                var pun = [];
                if (list.length == 0) {
                    str.id = 1;
                } else {
                    list.forEach(item => {
                        pun.push(item.id)
                    });
                    pun.sort(function (a, b) {
                        return a - b
                    });
                    var max = pun[pun.length - 1];
                    str.id = parseInt(max + 1);
                }
                list.push(str);
                write(list, function (err) {
                    console.log(err)
                })
                res.end(JSON.stringify({
                    "status": "success",
                    "result": {
                        "data": list,
                        "code": 10002,
                        "msg": "成功",
                    },
                }));
            })
        })
        return
    };

    if (pathname === '/onelist') {
        res.setHeader('Content-type', 'application/json;charset=utf8');
        var id = query.id;
        read(list => {
            list = list.filter(item => item.id == id);
            res.end(JSON.stringify({
                "status": "success",
                "result": {
                    "data": list,
                    "code": 10002,
                    "msg": "成功",
                },
            }))

        })
        return
    };

    if (pathname === '/changelist') {
        res.setHeader('Content-type', 'application/json;charset=utf8');
        var str = '';
        req.on('data', chunk => {
            str += chunk
        });
        req.on('end', () => {
            str = JSON.parse(str);
            // console.log(str);
            read(list => {
                var lost = list.map(item => {
                    if (item.id == str.id) {
                        return item = str;
                    }
                    return item;
                })
                console.log(lost);
                write(lost, err => {
                    console.log(err)
                });
                res.end(JSON.stringify({
                    "status": "success",
                    "result": {
                        "data": lost,
                        "code": 10002,
                        "msg": "成功",
                    },
                }))
            })
            // 
        });
        return
    }

});

server.listen(7070);